package com.lft.freshordering.controller;


import com.lft.freshordering.entity.Goods;
import com.lft.freshordering.entity.Stypes;
import com.lft.freshordering.response.R;
import com.lft.freshordering.response.StatusEnum;
import com.lft.freshordering.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tyhxzy
 * @since 2024-12-02
 */
@RestController
@RequestMapping("/lft/goods")
public class GoodsController {

    //处理图片的公共方法
    private byte[] handleFileUpload(MultipartFile file) throws IOException {
        // 判断文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        // 文件类型
        String substring = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println(substring);

        // 创建临时文件, 用于临时存储文件
        File tempFile = File.createTempFile("temp", file.getOriginalFilename());
        // 将上传的文件写入临时文件
        file.transferTo(tempFile);
        // 将文件转换为字节数组
        FileInputStream fis = new FileInputStream(tempFile);
        // 创建一个ByteArrayOutputStream对象
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 读取文件内容
        byte[] buf = new byte[1024];
        // 循环读取文件内容
        int len;
        while ((len = fis.read(buf)) != -1) {
            baos.write(buf, 0, len);
        }
        // 将字节数组转换为Base64编码
        byte[] bytes = baos.toByteArray();
        System.out.println("base64编码：" + bytes);

        return bytes;
    }

    @Autowired
    private IGoodsService goodsService;
    //查询所有商品
    @RequestMapping("/good")
    public R<List<Goods>> goods(){
        List<Goods> selectgoods = goodsService.selectgoods();
        if (selectgoods != null){
            return R.success(selectgoods);
        }else {
            return R.error(StatusEnum.SERVICE_ERROR);
        }
    }

    //商品分类id来查询
    @RequestMapping("/category/{id}")
    public R<List<Stypes>> category(@PathVariable("id") Integer id){
        System.out.println(id+"-=-=-=-=");
        List<Stypes> goods = goodsService.selectByCategoryId(id);
        if (goods != null){
            return R.success(goods);
        }else {
            return R.error(StatusEnum.SERVICE_ERROR);
        }
    }

    //根据商品id来查询
    @RequestMapping("/goodsid/{id}")
    public R<Goods> goods(@PathVariable Integer id) {
        System.out.println(id);
        Goods goods = goodsService.getById(id);
        if(goods!=null){
            return R.success(goods);
        }else {
            return R.error(StatusEnum.SERVICE_ERROR);
        }
    }

    //修改商品内容
    @RequestMapping("/update")
    public R<String> update(@RequestBody Goods goods) {
        System.out.println(goods+"-=-=-=-=-=-=-=-=-");
        Goods gg=new Goods();
        //商品id
        gg.setGoodsId(goods.getGoodsId());
        //商品名称
        gg.setGoodsName(goods.getGoodsName());
        //商品分类
        gg.setCategoryId(goods.getCategoryId());
        //商品介绍
        gg.setIntroduces(goods.getIntroduces());
        //商品品种
        gg.setVarietys(goods.getVarietys());
        //商品价格gjprices
        gg.setGjprices(goods.getGjprices());
        //商品单位
        gg.setGoodsUnit(goods.getGoodsUnit());
        System.out.println(gg+"-=-=-=-=-=-=-=-=-");
        int updategoods = goodsService.updategoods(gg);
        if (updategoods>0){
            return R.error(200, "修改成功");
        }else {
            return R.error(StatusEnum.SERVICE_ERROR);
        }
    }

    //修改商品图片
    @RequestMapping("/updateimg/{id}")
    public R<byte[]> updateimg(@PathVariable Integer id, @RequestParam("file") MultipartFile file){
        System.out.println("-=-=-=-=-=");

        try {
            byte[] bytes = handleFileUpload(file);
            Goods goods = new Goods();
            goods.setGoodsId(id);
            goods.setGoodsPics(bytes);

            int i = goodsService.save(goods);
            if (i>0){
                return R.success(bytes);
            }else {
                return R.error(500, "图片上传失败");
            }
        }catch (IOException e){
            return R.error(500, "文件读取失败");
        }
    }


    //删除商品
    @RequestMapping("/delete/{id}")
    public R<String> delete(@PathVariable Integer id){
        int updategoods = goodsService.deletegoods(id);
        if (updategoods>0){
            return R.success("删除成功");
        }else {
            return R.error(StatusEnum.SERVICE_ERROR);
        }
    }

    //存放图片
    @RequestMapping("/img")
    public R<byte[]> img(@RequestParam("file") MultipartFile file) throws IOException {
        byte[] bytes = handleFileUpload(file);
        Goods gg=new Goods();
        gg.setGoodsPics(bytes);
        return R.success(bytes);
    }

    //新增商品
    Integer instertgoods=null;
    @RequestMapping("/add")
    public R<String> add(@RequestBody Goods goods){
        Goods gg=new Goods();
        gg.setGoodsName(goods.getGoodsName());
        gg.setGoodsUnit(goods.getGoodsUnit());
        gg.setGjprices(goods.getGjprices());
        gg.setCategoryId(goods.getCategoryId());
        gg.setIntroduces(goods.getIntroduces());
        gg.setVarietys(goods.getVarietys());
        System.out.println(gg+"--==-----------qqqq");
        instertgoods = goodsService.instertgoods(gg);
        System.out.println(instertgoods+"--=-=-=-=-=-=-=-=-=-");
        if (instertgoods>0){
            return R.success("添加成功");
        }else {
            return R.error(StatusEnum.SERVICE_ERROR);
        }
    }

    //修改新增图片
    @RequestMapping("/tupian")
    public R<byte[]> tupian(MultipartFile file) {
        System.out.println(file+"---000---");
        try {
            byte[] bytes = handleFileUpload(file);
            Goods gg=new Goods();
            gg.setGoodsId(instertgoods);
            gg.setGoodsPics(bytes);
            int instertgoods = goodsService.instertgoods(gg);
            if (instertgoods>0){
                return R.success(bytes);
            }else {
                return R.error(500, "图片上传失败");
            }
        }catch (IOException e){
            return R.error(500, "文件读取失败");
        }


    }

    //模糊查询
    @RequestMapping("/search/{search}")
    public R<List<Goods>> search(@PathVariable String search) {
        System.out.println(search+"===ssssss");
        List<Goods> selectlike = goodsService.selectlike(search);
        if (selectlike != null){
            return R.success(selectlike);
        }else {
            return R.error(StatusEnum.SERVICE_ERROR);
        }
    }


}
